package com.yc.upload.web;

import com.yc.upload.bean.Result;
import com.yc.upload.bean.UploadProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class UploadDo {

    @Autowired
    UploadProperties properties;

    @GetMapping("config")
    UploadProperties properties(){
        return properties;
    }

    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file,
                         String type) throws IOException {
        UploadProperties.FileConfig fileConfig = properties.getConfig().get(type);
        String filename = file.getOriginalFilename(); // "1.jpg"
        String prefix = UUID.randomUUID().toString().replaceAll("-", "");
        String suffix = filename.replaceFirst("(.+)(\\.\\w+)","$2");
        filename = prefix + suffix;
        // 如果保存的文件夹不存在,则创建
        File dispath = new File(fileConfig.getDiskpath());
        if (!dispath.exists()) {
            boolean dirsCreated = dispath.mkdirs();
            if (!dirsCreated) {
                System.out.println("Failed to create directories.");
            }
        }

        File fileObj = new File(dispath, filename);
        file.transferTo(fileObj);
        String webPath = fileConfig.getWebpath().replaceFirst("\\*{1,2}", filename);
        return new Result(1,"文件上传成功",webPath);
    }
}
